using Locomotion;
using UnityEngine;

namespace Combat
{
    public class Shooter : MonoBehaviour
    {
        public Weapon CurrentWeapon => weapon;
        
        [SerializeField] private Weapon weapon;
        
        private Health _health;
        private Mover _mover;

        private Vector3 _aimDirection;
        private Vector3 _aimPosition;
        

        private void Awake()
        {
            _health = GetComponent<Health>();
            _mover = GetComponent<Mover>();
            
            _health.Died += Health_Died;
        }

        public void AimAtDirection(Vector3 aimDirection)
        {
            _aimDirection = aimDirection;
            weapon.transform.up = Vector3.Slerp(weapon.transform.up, aimDirection, 20f * Time.deltaTime);
        }

        public void AimAtPosition(Vector3 aimPosition)
        {
            _aimPosition = aimPosition;
            Vector3 aimDirection = (aimPosition - weapon.transform.position).normalized;
            AimAtDirection(aimDirection);
        }

        public void SetWeapon(Weapon newWeapon)
        {
            weapon.gameObject.SetActive(false);
            weapon = newWeapon;
            weapon.gameObject.SetActive(true);
        }

        public void Shoot()
        {
            if (!weapon.TryFire(_aimDirection, _aimPosition))
            {
                return;
            }
            
            Recoil();
        }
        
        private void Health_Died()
        {
            weapon.gameObject.SetActive(false);
        }

        private void Recoil()
        {
            _mover.Knock(-1f * _aimDirection, weapon.RecoilForce, 0.1f);
        }
    }
}